package com.cykj.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class HttpResponse {
    private SocketChannel socketChannel;

    public HttpResponse(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;

    }

    public void write(String s1, byte[] fileBytes) {
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 200 OK");
        sb.append("\r\n");
        sb.append("Content-Type:" + s1 + "; charset=utf-8");
        sb.append("Content-length:" + fileBytes.length);
        sb.append("\r\n");
        sb.append("\r\n");

        //开辟一个缓冲区
        ByteBuffer allocate = ByteBuffer.allocate(sb.toString().getBytes().length);
        //往缓冲区中添加内容
        allocate.put(sb.toString().getBytes());
        //将缓冲区进行读写转换
        allocate.flip();
        //将缓冲区的内容发送出去---缓冲区可读可写
        try {
            socketChannel.write(allocate);

            //创建一个缓冲区并填充一个字节数组的内容
            ByteBuffer wrap = ByteBuffer.wrap(fileBytes);

            //判断缓冲区是否还有内容
            while (wrap.hasRemaining()){
                socketChannel.write(wrap);
            }

            socketChannel.shutdownOutput();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
